package xcraft.xserver.persistence;

import org.hibernate.exception.SQLGrammarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import xcraft.xserver.XException;

public class PlanetDAO extends HibernateDaoSupport {

	private static final Logger logger = LoggerFactory.getLogger(PlanetDAO.class);
	
	public Planet createPlanet(Planet planet) {
		logger.debug("Creating planet {}", planet);
		HibernateTemplate template = getHibernateTemplate();
		try {
			template.persist(planet);
		}
		catch (InvalidDataAccessResourceUsageException e) {
			logger.error("Couldn't create planet: {}", e);
			SQLGrammarException ge = (SQLGrammarException)e.getCause(); 
			throw new XException(ge.getMessage(), ge.getSQLException().getNextException());
		}
		
		return getPlanetById(planet.getId());
	}
	
	public Planet getPlanetById(String id) {
		try {
			return (Planet) getHibernateTemplate().get(Planet.class, id);
		}
		catch (SQLGrammarException sge) {
			logger.error("Couldn't get planet {}", id);
			throw new XException(sge.getMessage(), sge.getSQLException().getNextException());
		}

	}

	public Planet updatePlanet(Planet planet) {
		logger.debug("Updating planet {}", planet);
		HibernateTemplate template = getHibernateTemplate();
		try {
			template.merge(planet);
		}
		catch (SQLGrammarException sge) {
			logger.error("Couldn't update planet {}", planet);
			throw new XException(sge.getMessage(), sge.getSQLException().getNextException());
		}

		return getPlanetById(planet.getId());
	}
	
	public void deletePlanet(String id) {
        Planet planet = getPlanetById(id);
		logger.debug("Deleteing planet {}", planet);
		try {
			getHibernateTemplate().delete(planet);
		}
		catch (SQLGrammarException sge) {
			logger.error("Couldn't delete planet {}", planet);
			throw new XException(sge.getMessage(), sge.getSQLException().getNextException());
		}

	}
	
}
